<!--
  -    Copyright (c) 2018-2025, lengleng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: lengleng (wangiegie@gmail.com)
  -->
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page.sync="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        :search.sync="searchForm"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @search-reset="resetChange"
      >
        <template
          slot="isFeeRequire"
          slot-scope="scope"
        >
          <el-tag
            v-if="scope.row.isFeeRequire==1"
            type="success"
            effect="dark"
          >
            是
          </el-tag>
          <el-tag
            v-else-if="scope.row.isFeeRequire==0"
            effect="dark"
          >
            否
          </el-tag>
        </template>
        <template
          slot="carStatus"
          slot-scope="scope"
        >
          <el-tag
            v-if="scope.row.carStatus==4"
            type="danger"
            effect="dark"
          >
            {{scope.row.carStatus | carStatusFilter(carStatus)}}
          </el-tag>
          <el-tag
            v-else-if="scope.row.carStatus==1"
            type="warning"
            effect="dark"
          >
            {{scope.row.carStatus | carStatusFilter(carStatus)}}
          </el-tag>
          <el-tag
            v-else-if="scope.row.carStatus==2"
            type="success"
            effect="dark"
          >
            {{scope.row.carStatus | carStatusFilter(carStatus)}}
          </el-tag>
          <el-tag
            v-else-if="scope.row.carStatus==3"
            effect="dark"
          >
            {{scope.row.carStatus | carStatusFilter(carStatus)}}
          </el-tag>
          <!-- <div
            style="font-weight:600;"
            :style="{'fontWeight':600,'color':scope.row.carStatus==1?'yellow':'#000'}"
          >{{scope.row.carStatus | carStatusFilter(carStatus)}}</div> -->
        </template>
        <template
          slot="businessAuth"
          slot-scope="scope"
        >
          <el-tag
            v-if="scope.row.businessAuth==1"
            type="success"
            effect="dark"
          >
            {{scope.row.businessAuth | businessAuthFilter}}
          </el-tag>
          <el-tag
            v-if="scope.row.businessAuth!=1"
            type="info"
            effect="dark"
          >
            {{scope.row.businessAuth | businessAuthFilter}}
          </el-tag>
          <!-- <div :style="{'fontWeight':600,'color':scope.row.businessAuth==1?'green':'#000'}">{{scope.row.businessAuth | businessAuthFilter}}</div> -->
        </template>
        <template slot="nameSearch">
          <el-autocomplete
            style="width:100%;"
            class="inline-input"
            v-model="searchForm.name"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            @select="handleSelect"
          ></el-autocomplete>
        </template>
        <template
          slot-scope="scope"
          slot="enterInTimeSearch"
        >
          <el-date-picker
            v-model="date.in"
            type="datetimerange"
            range-separator="~"
            start-placeholder="入场开始时间"
            end-placeholder="入场结束时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </template>
        <template
          slot="searchMenu"
          slot-scope="{row,size}"
        >
          <el-button
            :size="size"
            icon="el-icon-download"
            @click="searchexport(row)"
          >导出</el-button>
        </template>
        <template
          slot="menu"
          slot-scope="scope"
        >
          <el-button
            size="small"
            type="text"
            @click="detailAndEditShow(scope.row)"
          >查看</el-button>
          <el-button
            size="small"
            type="text"
            v-if='scope.row.carStatus==3||scope.row.carStatus==2||scope.row.carStatus==1'
            @click="ManualExit(scope.row)"
          >手动出场</el-button>
        </template>
        <template
          slot-scope="scope"
          slot="menuLeft"
        >
          <div class="inCar">在场车辆:<span>{{carCount}}</span>  <el-button class="inCar-bnt" type="primary" size="small" @click="showManual">手动出场</el-button></div>
          
          <el-tabs
            v-model="activeName"
            @tab-click="handleClick"
          >
            <el-tab-pane
              label="商用车"
              name="0"
            ></el-tab-pane>
            <el-tab-pane
              label="非商用车"
              name="1"
            ></el-tab-pane>
            <el-tab-pane
              label="待出场"
              name="3"
            ></el-tab-pane>
          </el-tabs>
        </template>
      </avue-crud>
      <el-dialog
          title="车辆详情"
          :visible.sync="isdetailAndEdit"
          width="60%"
          top="1vh"
          :before-close="handleClose"
          :close-on-click-modal="false"
          :close-on-press-escape="false">
          <div>
            <div class="text">
              <span style="margin-right: 30%;">RFID:{{form.rfId}}</span>
              <span>车辆状态：{{form.carStatus | carStatus}}</span>
            </div>
            <div class="text">
              入场时间：{{form.enterInTime | formaDate}}
            </div>
            <el-tabs v-model="tagsaCtiveName">
              <el-tab-pane label="详情" name="first">
                <div class="carMessage">车辆信息</div>
                <div class="particulars" >
                    <div class="particulars-top" style="margin-top: 30px;">
                      <div>商家名称：{{form.name}}</div>
                      <div>车辆品牌：{{form.carBrand}}</div>
                      <div>车辆类型：{{form.carType}}</div>
                    </div>
                    <div class="particulars-center" style="margin-top: 30px;">
                      <div>车牌号：{{form.carFrameNo}}</div>
                      <div>车辆颜色：{{form.carColor}}</div>
                      <div>是否金融车：{{form.isFinanceCar |FinanceCar}}</div>
                    </div>
                    <div class="particulars-buttom" style="margin-top: 30px;">
                      <div v-if="form.isFeeRequire==1">是否收费：是</div>
                      <div v-if="form.isFeeRequire==0">是否收费：否</div>
                      <div>停车费(元)：{{form.parkingFee}}</div>
                    </div>
                    <div style="margin-top: 30px;">
                      备注：{{form.remarks}}
                    </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="操作日志" name="second" style="margin-top: 30px;">
                <el-timeline :reverse="reverse">
                  <el-timeline-item
                    v-for="(activity, index) in activities"
                    :key="index"
                    :timestamp="activity.updateDate">
                    {{activity.modifyContent}}
                  </el-timeline-item>
                </el-timeline>
              </el-tab-pane>
            </el-tabs>
          </div>
      </el-dialog>
      <el-dialog
          title="车辆信息"
          :visible.sync="ManualFor"
          width="30%"
          top="1vh"
          :before-close="ManualForClose"
          :close-on-click-modal="false"
          :close-on-press-escape="false">
          <el-form :inline="true" :model="ManualForForm" class="demo-form-inline">
            <el-form-item label="车架号">
              <el-input v-model="ManualForForm.carFrameNo" placeholder="请输入车架号"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="findcar">查询</el-button>
            </el-form-item>
          </el-form>
          <el-form label-position="right" label-width="80px" :model="ManualForData" v-if="ManualForShow">
            <el-form-item label="车辆RFID："  label-width="100px">
              <div>{{ManualForData.rfId}}</div>
            </el-form-item>
            <el-form-item label="车架号："  label-width="100px">
              <div>{{ManualForData.carFrameNo}}</div>
            </el-form-item>
            <el-form-item label="商家："  label-width="100px">
              <div>{{ManualForData.name}}</div>
            </el-form-item>
            <el-form-item label="联系方式："  label-width="100px">
              <div>{{ManualForData.phone}}</div>
            </el-form-item>
            <el-form-item label="车辆品牌："  label-width="100px">
              <div>{{ManualForData.carBrand}}</div>
            </el-form-item>
            <el-form-item label="车辆类型："  label-width="100px">
              <div>{{ManualForData.carType}}</div>
            </el-form-item>
            <el-form-item label="授权信息："  label-width="100px">
              <div>{{ManualForData.businessAuth | businessAuthF}}</div>
            </el-form-item>
            <el-form-item label="是否免费："  label-width="100px">
              <div>{{ManualForData.isFeeRequire | FeeRequireCar}}</div>
            </el-form-item>
            <el-form-item label="是否金融车："  label-width="100px">
              <div>{{ManualForData.isFinanceCar | FinanceCar}}</div>
            </el-form-item>
            <el-form-item label="停车费："  label-width="100px">
              <div>{{ManualForData.parkingFee}}元</div>
            </el-form-item>
            <el-form-item label="车辆状态：" label-width="100px">
              <div>{{ManualForData.carStatus | carStatus}}</div>
            </el-form-item>
            <el-form-item v-if="ManualForData.carStatus==3">
              <el-button type="primary"  @click="enterAnArena()">确认出场</el-button>
              <el-button @click="ManualForClose">取消</el-button>
            </el-form-item>
          </el-form>
      </el-dialog>
      <!-- <detail
        ref="Detail"
        @refresh="updateList"
        @handleUpdate="handleUpdate"
      ></detail> -->
      <manual-exit
        ref="ManualExit"
        @refresh="updateList"
        @restartTime="restartTime"
      >

      </manual-exit>
    </basic-container>
  </div>
</template>

<script>
import { fetchList, getObj, addObj, putObj, delObj, exportExcel, Line, carCompany,getPancun,enterAnArena } from '@/api/crcar'
import { tableOption } from '@/const/crud/inventory/index.js'
import { PopUp } from '@/api/car/inventory'
import { mapGetters } from 'vuex'
// import Detail from './Detail'
import ManualExit from './ManualExit'
import { getDicType,OperationLog } from '@/api/common'
export default {
  name: 'crcar',
  components: {
    // 'detail': Detail,
    'manual-exit': ManualExit
  },
  data () {
    return {
      reverse:false,
      ManualForShow:false,
      isdetailAndEdit:false,
      ManualFor:false,
      tagsaCtiveName:'first',
      activities:[],//查看日志
      form:{},
      searchForm: {
        name: '',
        isBusinessCar: 0,
        carStatus: '',
        type: 1
      },
      date: {
        in: []
      },
      tableData: [

      ],
      activeName: 0,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
      tabActiveName: '0',
      carCount: 0,
      PopUpInterval: null,
      restaurants: [],
      carStatus: [],
      ManualForForm:{
        carFrameNo:''
      },
      ManualForData:{},
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList () {
      return {
        addBtn: this.vaildData(this.permissions.car_crcar_add, false),
        delBtn: this.vaildData(this.permissions.car_crcar_del, false),
        editBtn: this.vaildData(this.permissions.car_crcar_edit, false)
      };
    }
  },
  created () {
    // this.initWebSocket()
     
  },
  mounted () {
    if (this.PopUpInterval) {
      clearInterval(this.PopUpInterval)
    }
    carCompany().then(({ data }) => {
      // this.restaurants = data.data
      for (let key in data.data) {
        this.restaurants.push({ value: key, label: data.data[key] })
      }
    })
    getDicType('car_status').then(({ data }) => {
      this.carStatus = data.data
    })
    this.startTime()
  },
  filters: {
    businessAuthF(val){
      if(val==0){
        return '未授权'
      }
      if(val==1){
        return '已授权'
      }
    },
    businessAuthFilter (val) {
      let list = [
        {
          label: "商家未授权",
          value: 0
        },
        {
          label: "商家已授权",
          value: 1
        }
      ]
      let str = ''
      list.forEach(item => {
        if (item.value === val) {
          str = item.label
        }
      })
      return str
    },
    FinanceCar(val){
      if(val==0){
        return '是'
      }
      if(val==1){
        return '否'
      }
    },
    FeeRequireCar(val){
      if(val==0){
        return '免费车'
      }
      if(val==1){
        return '收费车'
      }
    },
    carStatus(val){
      if(val==1){
        return '已确认 待确认'
      }
      if(val==2){
        return '已确认进场'
      }
      if(val==3){
        return '待出场'
      }
      if(val==4){
        return '已进场'
      }
      if(val==5){
        return '待进场'
      }
    },
    formaDate (val) {
      if (val) {
        return val.substring(0, 19)
      } else {
        return ''
      }
    },
    
    carStatusFilter (val, carStatus) {
      let str = ''
      carStatus.forEach(item => {
        if (item.value == val) {
          str = item.label
        }
      })
      return str
    }
  },
  methods: {
    detailAndEditShow(row){
      //查看弹窗
      this.form = row
      this.isdetailAndEdit=true
      let url = '/config/sysoperationlog/' + this.form.id + '/2'
        OperationLog(url).then(response => {
          this.activities = response.data.data
          // console.log(this.activities);
          console.log(this.form);
        })
    },
    handleClose(){
      //关闭弹窗
      this.isdetailAndEdit=false
      this.form = {}
    },
    handleSelect (item) {
      console.log(item);
    },
    querySearch (queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      var newresults = []
      results.forEach(item => {
        newresults.push({ value: item.label })
      })
      // 调用 callback 返回建议列表的数据
      // cb(results);
      cb(newresults)
    },
    createFilter (queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) != -1);
      };
    },
    restartTime () {
      if (this.PopUpInterval) {
        clearInterval(this.PopUpInterval)
      }
      this.startTime()
    },
    startTime () {
      this.PopUpInterval = setInterval(() => {
        if (this.$route.path === '/car/inventory/index') {
          PopUp().then(res => {
            if (res.data.data.id) {
              clearInterval(this.PopUpInterval)
              this.$refs.ManualExit.init(res.data.data)
            }
          })
        } else {
          clearInterval(this.PopUpInterval)
        }
      }, 3000)
    },
    initWebSocket () {
      this.connection()
      const self = this
      // 断开重连机制,尝试发送消息,捕获异常发生时重连
      this.timer = setInterval(() => {
        try {
          self.stompClient.send('test')
        } catch (err) {
          console.log('断线了: ' + err)
          self.connection()
        }
      }, 5000)
    },
    connection () {
      const token = store.getters.access_token
      const TENANT_ID = getStore({ name: 'tenantId' }) ? getStore({ name: 'tenantId' }) : '1'
      const headers = {
        'Authorization': 'Bearer ' + token
      }
      // 建立连接对象
      this.socket = new SockJS('/act/ws')// 连接服务端提供的通信接口，连接以后才可以订阅广播消息和个人消息
      // 获取STOMP子协议的客户端对象
      this.stompClient = Stomp.over(this.socket)
      this.stompClient.debug = null
      // 向服务器发起websocket连接
      this.stompClient.connect(headers, () => {
        this.stompClient.subscribe('/task/' + this.userInfo.username + '-' + TENANT_ID + '/remind', (msg) => { // 订阅服务端提供的某个topic;
          this.$notify({
            title: '协同提醒',
            type: 'warning',
            dangerouslyUseHTMLString: true,
            message: msg.body + '任务，请及时处理',
            offset: 60
          })
        })
      }, (err) => {

      })
    },
    disconnect () {
      if (this.stompClient != null) {
        this.stompClient.disconnect()
        console.log('Disconnected')
      }
    },
    // 导出功能
    searchexport (row, params) {
      this.tableLoading = true
      if (this.activeName == 3) {
        this.searchForm.isBusinessCar = ''
        // this.searchForm.carStatus = '3'
      } else {
        this.searchForm.isBusinessCar = parseInt(this.activeName)
      }
      // this.searchForm.carStatus = this.tabActiveName
      // this.searchForm.carStatus = null
      if (this.activeName === '0') {
        this.searchForm.type = 5
      } else if (this.activeName === '1') {
        this.searchForm.type = 6
      } else if (this.activeName === '2') {
        this.searchForm.type = 6
      }
      exportExcel(Object.assign({
        current: page.currentPage,
        size: page.pageSize,
      }, params, this.searchForm, { carStatus: (this.activeName == 3 || this.activeName == 0) ? this.searchForm.carStatus : null })).then(response => {
        if (!response) {
          return
        }
        let link = document.createElement('a')
        link.href = window.URL.createObjectURL(new Blob([response.data]))
        link.target = '_blank'
        let filename = response.headers['content-disposition']
        link.download = decodeURI(filename)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 进场车辆和出场车辆切换
    tabhandleClick () {
      this.getList(this.page)
      if (this.tabActiveName !== '4') {
        this.tableOption.column.splice(8, 1)
      } else {
        this.tableOption.column.splice(8, 1, {
          "type": "datetime",
          "search": true,
          "label": "出场时间",
          hide: false,
          "prop": "comeOutTime",
          format: "yyyy-MM-dd HH:mm:ss",
          valueFormat: "yyyy-MM-dd HH:mm:ss"
        })
      }
    },
    // tabs 选择tabs切换动作
    handleClick () {
      this.getList(this.page)
      if (this.activeName == '0') {
        this.tableOption.column[1].hide = true
        this.tableOption.column[2].hide = false
        this.tableOption.column[1].search = false
        this.tableOption.column[2].search = true
      } else if (this.activeName == '1') {
        this.tableOption.column[1].hide = false
        this.tableOption.column[2].hide = true
        this.tableOption.column[1].search = true
        this.tableOption.column[2].search = false
      } else if (this.activeName == '3') {
        this.tableOption.column[1].hide = true
        this.tableOption.column[2].hide = false
        this.tableOption.column[1].search = false
        this.tableOption.column[2].search = true
      }
    },
    // 查看对应数据的详情
    // Detailid (row) {
    //   console.log(row);
    //   // this.$refs.Detail.init(row.id, this.activeName, this.tabActiveName)
    //   this.
    // },
    // 手动出场
    ManualExit (row) {
      // this.$message.success("开发中")
      if (this.PopUpInterval) {
        clearInterval(this.PopUpInterval)
      }
      this.$refs.ManualExit.init(row)
    },
    updateList () {
      this.getList(this.page)
    },
    getList (page, params) {
      this.tableLoading = true

      if (this.activeName == 3) {
        this.searchForm.isBusinessCar = ''
        // this.searchForm.carStatus = '3'
      } else {
        this.searchForm.isBusinessCar = parseInt(this.activeName)
      }
      if (this.date.in && this.date.in.length == 2) {
        this.searchForm.startInTime = this.date.in[0]
        this.searchForm.endInTime = this.date.in[1]
      }

      // this.searchForm.carStatus = this.tabActiveName === '0' ? '' : this.tabActiveName
      fetchList(Object.assign({
        current: page.currentPage,
        size: page.pageSize,
      }, params, this.searchForm, { carStatus: (this.activeName == 3 || this.activeName == 0) ? this.searchForm.carStatus : null })).then(response => {
        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
      Line({}).then(response => {
        this.carCount = response.data.data
      })
    },
    rowDel: function (row, index) {
      this.$confirm('是否确认删除此条数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delObj(row.id)
      }).then(data => {
        this.$message.success('删除成功')
        this.getList(this.page)
      })
    },
    handleUpdate: function (row, index, done, loading) {
      putObj(row).then(data => {
        this.$message.success('修改成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        if (loading) {
          loading();
        }
      });
    },
    handleSave: function (row, done, loading) {
      addObj(row).then(data => {
        this.$message.success('添加成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        if (loading) {
          loading();
        }
      });
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize
      this.getList(this.page)
    },
    currentChange (current) {
      this.page.currentPage = current
      this.getList(this.page)
    },
    searchChange (form, done) {
      this.searchForm = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    refreshChange () {
      this.getList(this.page)
    },
    resetChange () {
      this.date.in = []
      this.getList(this.page)
    },
    showManual(){
      //显示手动出场
      this.ManualFor=true
    },
    ManualForClose(){
      //关闭手动出场弹框
      this.ManualFor=false
      this.ManualForShow=false
      this.ManualForData={}
      this.ManualForForm.carFrameNo=''
    },
    async findcar(){
      //根据车架号查询车辆
      try{
        const {data:res} = await getPancun(this.ManualForForm)
        if(!res.data.data){
          this.$message.error('无车辆信息')
          this.ManualForShow=false
          this.ManualForData={}
          return
        }
        this.ManualForData=res.data.data
        this.ManualForShow=true
        console.log(this.ManualForData);
      }catch(error){
        this.$message.error(error)
      }
    },
    async enterAnArena(){//手动出场
      try{
        let id = this.ManualForData.id       
        const {data:res} = await enterAnArena(id)
        if(res.code==0){
          this.ManualForClose()
          this.$message.success('已确认出场')
        }
      }catch(error){
        this.$message.error(error)
      }
    },
  }
}
</script>
<style lang="scss" scoped>
.carMessage{
  margin-top: 20px;
}
.particulars{
  .particulars-top{
    display: flex;
    div{
      width: 33%;
    }
  }
  .particulars-center{
    display: flex;
    div{
      width: 33%;
    }
  }
  .particulars-buttom{
    display: flex;
    div{
      width: 33%;
      
    }
  }
}
.text{
  font-size:20px ;
  color: #666;
  margin-bottom: 20px;
}
.inCar {
  font-weight: 600;
  font-size: 28px;
  position: relative;
  .inCar-bnt{
    position:absolute;
    top:5px;
    margin-left: 20px;
    margin-top: 0px;
    
  }
  span {
    color: #4d4df7;
  }
}
</style>